<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目编号" prop="projectCode">
        <el-input
          v-model="queryParams.projectCode"
          placeholder="请输入项目编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目名称" prop="projectName">
        <el-input
          v-model="queryParams.projectName"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目地址" prop="projectAddress">
        <el-input
          v-model="queryParams.projectAddress"
          placeholder="请输入项目地址"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="总包方" prop="projectGeneralContractorDeptId">
        <el-input
          v-model="queryParams.projectGeneralContractorDeptId"
          placeholder="请输入项目总包方"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="更新时间">
        <el-date-picker
          v-model="daterangeUpdateTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['app:project:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['app:project:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['app:project:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['app:project:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="projectList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="id" align="center" prop="projectId"/>
      <el-table-column label="项目编号" align="center" prop="projectCode"/>
      <el-table-column label="项目名称" align="center" prop="projectName"/>
      <el-table-column label="项目地址" align="center" prop="projectAddress"/>
      <el-table-column label="项目甲方" align="center" prop="projectFirstPartyDept.deptName"/>
      <el-table-column label="总包方" align="center" prop="projectGeneralContractorDept.deptName"/>
      <el-table-column label="供货方" align="center" prop="projectSupplierDept.deptName"/>
      <el-table-column label="联络员" align="center">
        <template slot-scope="scope">
          <label-tag :options="userOptions" :value="scope.row.businessManIds"/>
        </template>
      </el-table-column>
      <el-table-column label="维护员" align="center">
        <template slot-scope="scope">
          <label-tag :options="userOptions" :value="scope.row.maintenanceManIds"/>
        </template>
      </el-table-column>
      <el-table-column label="项目经度" align="center" prop="projectLongitude"/>
      <el-table-column label="项目纬度" align="center" prop="projectLatitude"/>
      <el-table-column label="项目LOGO" align="center" prop="projectImage" width="300">
        <template slot-scope="scope">
          <image-preview :src="scope.row.projectImage" :width="100" :height="100"/>
        </template>
      </el-table-column>
      <el-table-column label="三维版本" align="center" prop="modelVersion"/>
      <el-table-column label="APP版本" align="center" prop="appVersion"/>
      <el-table-column label="APP二维码" align="center" prop="appQR" width="300">
        <template slot-scope="scope">
          <image-preview :src="scope.row.appQR" :width="100" :height="100"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['app:project:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-upload"
            @click="handleUpdateFile(scope.row,'1')"
            v-hasPermi="['app:project:edit']"
          >上传三维文件
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-upload"
            @click="handleUpdateFile(scope.row,'2')"
            v-hasPermi="['app:project:edit']"
          >上传App文件
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['app:project:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改项目管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="750px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="项目编号" prop="projectCode">
          <el-input v-model="form.projectCode" placeholder="请输入项目编号"/>
        </el-form-item>
        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="form.projectName" placeholder="请输入项目名称"/>
        </el-form-item>
        <el-form-item label="项目地址" prop="projectAddress">
          <el-input v-model="form.projectAddress" placeholder="请输入项目地址"/>
        </el-form-item>
        <el-form-item label="项目甲方" prop="projectFirstPartyDeptId">
          <treeselect v-model="form.projectFirstPartyDeptId" :options="deptOptions" :show-count="true"
                      placeholder="请选择项目甲方"/>
        </el-form-item>
        <el-form-item label="总包方" prop="projectGeneralContractorDeptId">
          <treeselect v-model="form.projectGeneralContractorDeptId" :options="deptOptions" :show-count="true"
                      placeholder="请选择项目总包方"/>
        </el-form-item>
        <el-form-item label="供货方" prop="projectSupplierDeptId">
          <treeselect v-model="form.projectSupplierDeptId" :options="deptOptions" :show-count="true"
                      placeholder="请选择项目供货方"/>
        </el-form-item>
        <el-form-item label="联络员" prop="businessManIds">
          <el-select v-model="form.businessManIds" multiple placeholder="请选择联络员">
            <el-option
              v-for="item in userOptions"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId"
              :disabled="item.status == 1"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="维护员" prop="maintenanceManIds">
          <el-select v-model="form.maintenanceManIds" multiple placeholder="请选择维护员">
            <el-option
              v-for="item in userOptions"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId"
              :disabled="item.status == 1"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="项目LOGO图片" >
          <image-upload :file-list="form.projectImage" :limit="1" :multiple="false"  :on-change="projectPicChange" />
        </el-form-item>
        <el-form-item label="项目经度" prop="projectLongitude">
          <el-input v-model="form.projectLongitude" placeholder="请输入项目经度"/>
        </el-form-item>
        <el-form-item label="项目纬度" prop="projectLatitude">
          <el-input v-model="form.projectLatitude" placeholder="请输入项目纬度"/>
        </el-form-item>
        <el-form-item label="地址">
          <div class="map" ref="map">
            <!-- 地图实例 -->
            <baidu-map
              class="bmView"
              :scroll-wheel-zoom="true"
              :center="location"
              :zoom="zoom"
              @ready="handler"
              @click="getClickInfo"
              ak="1pvlG1Zt7oOXLFOWKh8lupORIYhZOxWQ"
            >
              <!-- 地图显示 -->
              <bm-view style="width: 100%; height: 400px; flex: 1"></bm-view>
              <!-- 标记点组件 -->
              <bm-marker
                :position="{ lng: location.lng, lat: location.lat }"
              ></bm-marker>
              <!-- 搜索控件 -->
              <bm-control>
                <bm-auto-complete
                  v-model="form.address"
                  :sugStyle="{ zIndex: 999999 }"
                  @confirm="handleConfirm"
                >
                  <el-input
                    v-model="form.address"
                    placeholder="请输入地址来直接查找相关位置"
                    style="width: 500px"
                  ></el-input>
                </bm-auto-complete>
              </bm-control>
            </baidu-map>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 三维导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <div style="position: relative">
        <div v-if="upload.startUpload" style="position: absolute; top: 0; left: 0; height: 100%; width: 100%; background: rgba(0,0,0,0.1);z-index: 2002;display: flex; align-items: center;justify-content: center">
            <span style="color: red">上传中，请勿关闭此对话框</span>
        </div>
        <el-upload
          ref="upload"
          :limit="1"
          :accept="upload.type === '1' ? '.glb':'.apk'"
          action=""
          :before-upload="handleBeforeUpload"
          :on-error="handleUploadError"
          :on-exceed="handleExceed"
          :on-success="handleUploadSuccess"
          :http-request="uploadOSS"
          :show-file-list="false"
          drag
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip text-center" slot="tip">
            <div class="el-upload__tip" slot="tip">
              <div>
                <el-progress :text-inside="true" :stroke-width="26" :percentage="percentageFile"
                             status="success"></el-progress>
              </div>
              <div style="display: flex;align-items: center;margin-top: 12px">
                <span style="color: red;margin-right: 12px;font-size: 18px">*</span>
                <el-input v-model="upload.version" size="mini" placeholder="请输入版本号"/>
              </div>
            </div>
            <div style="padding: 12px 0; text-align: left; color: red">{{upload.type === '1' ? '仅允许导入glb格式文件。' : '仅允许导入apk格式文件。'}}</div>
          </div>
        </el-upload>
      </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitFormFile" :disabled="percentageFile !== 100">确 定</el-button>
          <el-button @click="upload.open = false" :disabled="upload.startUpload">取 消</el-button>
        </div>
    </el-dialog>
  </div>
</template>

<script>
import {deptTreeSelect, listAllUser} from "@/api/system/user";
import {addProject, delProject, getProject, listProject, updateProject} from "@/api/app/project";
import {BaiduMap, BmAutoComplete, BmControl, BmMarker, BmView} from "vue-baidu-map";
import {getToken} from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {uploadFile} from "@/utils/miniooss";

export default {
  name: "Project",
  components: {
    BaiduMap,
    BmMarker,
    BmView,
    BmControl,
    BmAutoComplete,
    Treeselect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目管理表格数据
      projectList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      // 部门树选项
      deptOptions: undefined,
      // 人员选项
      userOptions: undefined,
      open: false,
      // 更新时间时间范围
      daterangeUpdateTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectCode: null,
        projectName: null,
        projectAddress: null,
        projectGeneralContractorDeptId: null,
        updateTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        projectCode: [
          {required: true, message: "项目编号不能为空", trigger: "blur"}
        ],
        projectName: [
          {required: true, message: "项目名称不能为空", trigger: "blur"}
        ],
        projectAddress: [
          {required: true, message: "项目地址不能为空", trigger: "blur"}
        ],
        projectLatitude: [
          {required: true, message: "项目纬度不能为空", trigger: "blur"}
        ],
        projectLongitude: [
          {required: true, message: "项目经度不能为空", trigger: "blur"}
        ],
        projectFirstPartyDeptId: [
          {required: true, message: "项目甲方不能为空", trigger: "blur"}
        ],
        projectGeneralContractorDeptId: [
          {required: true, message: "项目总包方不能为空", trigger: "blur"}
        ],
        projectSupplierDeptId: [
          {required: true, message: "供货方不能为空", trigger: "blur"}
        ],
        businessManIds: [
          {required: true, message: "联络员不能为空", trigger: "blur"}
        ],
        maintenanceManIds: [
          {required: true, message: "维护员不能为空", trigger: "blur"}
        ]
      },
      BMap: null,
      map: null,
      // 地图显示的中心坐标
      location: {
        lng: 121.510814,
        lat: 31.292523,
      },
      // 缩放，15基本上就可以看附近的一些街道了
      zoom: 15,
      keyWord: "",
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        version: "",
        type: null,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData",
        startUpload: false
      },
      percentageFile: 0,
    };
  },
  created() {
    this.getAllUser();
    // this.getList();
    this.getDeptTree();
  },
  methods: {
    /** 查询项目管理列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeUpdateTime && '' != this.daterangeUpdateTime) {
        this.queryParams.params["beginUpdateTime"] = this.daterangeUpdateTime[0];
        this.queryParams.params["endUpdateTime"] = this.daterangeUpdateTime[1];
      }
      listProject(this.queryParams).then(response => {
        this.projectList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    }, /** 查询人员 */
    getAllUser() {
      listAllUser().then(response => {
        this.userOptions = response.data;
        this.getList()
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.handleQuery();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        projectId: null,
        projectCode: null,
        projectName: null,
        projectAddress: null,
        projectLongitude: null,
        projectLatitude: null,
        projectFirstPartyDeptId: null,
        projectGeneralContractorDeptId: null,
        projectSupplierDeptId: null,
        businessMan: null,
        maintenanceMan: null,
        businessManIds: null,
        maintenanceManIds: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        modelVersion: null,
        modelFile: null,
        appVersion:null,
        appFile: null,
        appQR:null,
        projectImage:null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeUpdateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.projectId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加项目管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const projectId = row.projectId || this.ids
      getProject(projectId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改项目管理";
      });
    },
    handleUpdateFile(row,type) {
      this.reset();
      const projectId = row.projectId || this.ids
      getProject(projectId).then(response => {
        this.form = response.data;
          this.upload.type = type;
          this.upload.title = type === '1' ? "上传三维文件" : "上传App文件" ;
          this.upload.open = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.businessMan = this.form.businessManIds + ""
          this.form.maintenanceMan = this.form.maintenanceManIds + ""
          if (this.form.projectId != null) {
            updateProject(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProject(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    submitFormFile(){
      updateProject(this.form).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.upload.open = false;
        this.getList();
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const projectIds = row.projectId || this.ids;
      this.$modal.confirm('是否确认删除项目管理编号为"' + projectIds + '"的数据项？').then(function () {
        return delProject(projectIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('app/project/export', {
        ...this.queryParams
      }, `project_${new Date().getTime()}.xlsx`)
    },

    handler({BMap, map}) {
      this.BMap = BMap;
      this.map = map;
    },
    handleConfirm({item}) {
      const that = this;
      let queryString = `${item.value.city}${item.value.district}${item.value.business}`;
      var myGeo = new BMap.Geocoder();
      myGeo.getPoint(queryString, function (point) {
        if (point) {
          console.log(point, "point");
          that.location = point;
          that.form.projectLongitude = that.location.lng;
          that.form.projectLatitude = that.location.lat
        }
      });
    },
    // 地图点击事件
    getClickInfo(e) {
      this.map.clearOverlays();
      const myMarker = new BMap.Marker(new BMap.Point(e.point.lng, e.point.lat));
      this.map.addOverlay(myMarker);
      this.location.lng = e.point.lng;
      this.location.lat = e.point.lat;
      this.form.projectLongitude = this.location.lng;
      this.form.projectLatitude = this.location.lat

    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      if (!this.upload.version) {
        this.$message.warning("必须先填写版本号");
        return false;
      }else if (!this.upload.version && this.form.modelVersion === this.upload.version){
        this.$message.warning("版本号相同，不能上传");
        return false;
      }
      // 校检文件类型
      let fileExtension = "";
      if (file.name.lastIndexOf(".") > -1) {
        fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
      }
      let fileType = this.upload.type === '1' ? 'glb' : 'apk';
      const isTypeOk = () => {
        if (file.type.indexOf(fileType) > -1) return true;
        return !!(fileExtension && fileExtension.indexOf(fileType) > -1);
      }
      if (!isTypeOk) {
        this.$message.error('文件格式不正确, 请上传'+fileType+'格式文件!');
        return false;
      }
      this.upload.startUpload = true;
      return true;
    },
    // 文件个数超出
    handleExceed() {
      this.upload.startUpload = false;
      this.$message.error(`只允许上传单个文件`);
    },
    // 上传失败
    handleUploadError(err) {
      this.upload.startUpload = false;
      this.$message.error("上传失败, 请重试");
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      this.$message.success("上传成功");
      let url = res.url;
      if (url.indexOf('?') > -1){
        url = url.split("?")[0];
      }else {
        url = res.url;
      }
      if (this.upload.type === '1'){
        this.form.modelFile = url;
        this.form.modelVersion = this.upload.version;
      }else if (this.upload.type === '2'){
        this.form.appFile = url;
        this.form.appVersion = this.upload.version;
      }
      this.upload.startUpload = false;
    },
    // 获取文件名称
    getFileName(name) {
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1).toLowerCase();
      } else {
        return "";
      }
    },
    uploadOSS(file) {
      const _this = this;
      uploadFile(file.file, error => {
        console.log(error)
        this.handleUploadError()
      }, success => {
        console.log(success)
        if (success && success.url) {
          this.handleUploadSuccess(success)
        }
      }, process => {
        process = process.toString().replaceAll("%", '');
        process = parseInt(process);
        this.percentageFile = process;
        console.log(process)
      })
    },
    projectPicChange(e){
      this.form.projectImage = e;
    }
  }
};
</script>
